package org.dromara.xxmj.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.*;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.*;
import org.dromara.common.tenant.exception.TenantException;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.xxmj.domain.CourseSimulation;
import org.dromara.xxmj.domain.vo.CourseGeneralVO;
import org.dromara.xxmj.domain.vo.CourseSimulationVO;
import org.dromara.xxmj.mapper.CourseSimulationMapper;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * GIT-zaixianjiaoyu
 *
 * @param
 * @Author 王晨沣
 * @Date 2025-05-14 09:15:38 （可以根据需要修改）
 */
@Slf4j
@Repository
public class CheckUtils {

    @Resource
    private CourseSimulationMapper courseSimulationMapper;//模拟题库

    @Resource
    private  SysUserMapper userMapper;

    /**
     *
     * @Author 王晨沣 2307105054
     * @Date 2025-05-17 16:43:59
     */
    public void checkUser(SysUserVo user) {
        String uuid = Convert.toStr(user.getUserId(),"1");
        if (!TenantHelper.isEnable()) {
            return;
        }
        if (StringUtils.isBlank(uuid)) {
            throw new TenantException("uuid.number.not.blank");
        }
        //超级管理员不用校验
        if (TenantConstants.SUPER_ADMIN_ID_STR.equals(uuid)) {
            user.setUserId(123456L);
            return;
        }
        if (ObjectUtil.isNull(uuid)) {
            log.info("登录用户：{} 不存在.", uuid);
            throw new TenantException("uuid.not.exists");
        } else if (SystemConstants.DISABLE.equals(user.getStatus())) {
            log.info("登录租户：{} 已被停用.", uuid);
            throw new TenantException("uuid.blocked");
        }
    }

    public void checkAdmin(LoginUser user) {
        String uuid = Convert.toStr(user.getUserId(),"");
        if (StrUtil.isEmpty(uuid)){
            user.setUserId(123456L);
        }
    }

    /**
     * 检查答案是否正确
     */
    public boolean checkAnswer(CourseGeneralVO exercise, String userAnswer) {
        String correctAnswer = exercise.getAnswer();
        String type = exercise.getType();

        if ("0".equals(type) || "2".equals(type)) {
            // 单选题或判断题，直接比较
            return correctAnswer.equals(userAnswer);
        } else if ("1".equals(type)) {
            // 多选题，需要排序后比较
            String[] correctParts = correctAnswer.split(",");
            String[] userParts = userAnswer.split(",");

            Arrays.sort(correctParts);
            Arrays.sort(userParts);

            return Arrays.equals(correctParts, userParts);
        }
        return false;
    }


    /**
     * 检查模拟卷答案是否正确,并加上分值
     */
    public void checkSimulationAnswer(CourseGeneralVO exercise, String userAnswer,Double totalScore,int isCorrect) {
        LambdaQueryWrapper<CourseSimulation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseSimulation::getId, exercise.getId()).eq(CourseSimulation::getCourseId, exercise.getCourseId())
            .eq(CourseSimulation::getSimulationId,exercise.getSimulationId());
        CourseSimulationVO courseSimulationVO = courseSimulationMapper.selectVoOne(queryWrapper);
        if (courseSimulationVO == null){
            throw new IllegalArgumentException("未找到此试题，请联系管理员处理！");
        }

        Double score = courseSimulationVO.getScore();
        String correctAnswer = courseSimulationVO.getAnswer();
        String type = courseSimulationVO.getType();
        if ("0".equals(type) || "2".equals(type)) {
            // 单选题或判断题，直接比较
            if (correctAnswer.equals(userAnswer)) {
                totalScore += score;
                isCorrect = 1;
            }
        } else if ("1".equals(type)) {
            // 多选题，需要排序后比较
            String answer = courseSimulationVO.getAnswer(); // 正确答案
            String[] answers = answer.split(","); // 拆分为单个答案数组
            // 获取题目总分

            // 计算每项答案对应的分数
            double oneScore = Convert.toDouble(score, 0.0) / answers.length;
            oneScore = Math.round(oneScore * 100) / 100.0; // 保留两位小数

            for (String correct : answers) {
                if (userAnswer.contains(correct)) {
                    totalScore += oneScore; // 如果用户答案匹配正确答案项，则加分
                    isCorrect = 1;
                }
            }
//            String[] correctParts = correctAnswer.split(","); //正确答案
//            String[] userParts = userAnswer.split(","); //用户答案
//
//            Arrays.sort(correctParts);
//            Arrays.sort(userParts);
//            String answer = courseSimulationVO.getAnswer(); //正确答案
//            String answerStr = answer.toLowerCase(); //小写
//
//            String[] answers = StringUtils.split(answer, ","); //正确答案
//
//            Double score = courseSimulationVO.getScore();
//            double oneScore = Convert.toDouble(score, 0.0) / answers.length;
//            oneScore = Math.round(oneScore * 100) / 100.0;
//
//
//
//
//            for (String oneAnswer : answers) {
//                if (answerStr.contains(oneAnswer.toLowerCase())) {
//                    totalScore += oneScore;
//                }
//            }
            if (correctAnswer.equals(userAnswer)) {
                totalScore += score;
                isCorrect = 1;
            }
//            isCorrect = correctAnswer.equals(userAnswer);
//            return Arrays.equals(correctParts, userParts);
        } else if ("3".equals(type)) {
            String answer = courseSimulationVO.getAnswer(); //正确回答
            String answerStr = answer.toLowerCase(); //小写

            String[] answers = StringUtils.split(answer, ",");
            double oneScore = Convert.toDouble(score, 0.0) / answers.length;
            oneScore = Math.round(oneScore * 100) / 100.0;
            for (String oneAnswer : answers) {
                if (answerStr.contains(oneAnswer.toLowerCase())) {
                    totalScore += oneScore;
                }
            }
            if (correctAnswer.equals(userAnswer)) {
                totalScore += score;
                isCorrect = 1;
            }
//            return correctAnswer.equals(userAnswer);
        }

//        return false;
    }


}
